// openssl genrsa -out certs/server/my-server.key.pem 2048
// openssl rsa -in certs/server/my-server.key.pem -pubout -out certs/client/my-server.pub

'use strict';

var fs = require('fs')
    , ursa = require('ursa')
    , sshPublicKrt
    , pemPublicKrt
    , privateKey
    , msg
    , msg1
    , msg2
    ;

/*通过私钥创建rsa对象*/
privateKey = ursa.createPrivateKey(fs.readFileSync('./id_rsa'));
/*通过公钥创建rsa对象*/
sshPublicKrt = ursa.openSshPublicKey( new Buffer(fs.readFileSync('./id_rsa.pub').toString("utf8").slice(8), "base64"));
pemPublicKrt = ursa.createPublicKey(fs.readFileSync('./id_rsa_pem.pub'));

console.log('通过公钥加密：');
msg = sshPublicKrt.encrypt("这是一串需要加密的密码");
msg1 = pemPublicKrt.encrypt("这是一串需要加密的密码");
console.log('ssh格式加密之后的是：', msg, '\n');
console.log('pem格式加密之后的是：', msg1, '\n');

console.log('通过私钥解密');
msg = privateKey.decrypt(msg, 'base64', 'utf8');
msg1 = privateKey.decrypt(msg1, 'base64', 'utf8');
console.log('ssh解密之后的字符是：', msg, '\n');
console.log('pem解密之后的字符是：', msg1, '\n');

console.log('############################################');
console.log('上面是公钥加密，私钥解密；下面是私钥加密，公钥解密');
console.log('############################################\n');

console.log('通过私钥加密：');
msg = privateKey.privateEncrypt("a=123");
console.log('加密之后的是：', msg, '\n');

console.log('通过公钥解密');
msg1 = sshPublicKrt.publicDecrypt(msg, 'base64', 'utf8');
msg2 = sshPublicKrt.publicDecrypt(msg, 'base64', 'utf8');
console.log('ssh解密之后的字符是：', msg1, '\n');
console.log('pem解密之后的字符是：', msg2, '\n');